// pages/mapPage/mapPage.js
/*
  1. 根据用户配置，返回当前用户组下激活的地图-图层-点数据
  2. 维护图层数据及点数据即可，存入全局数据（一颗树），切换地图是更新树即可
*/
import {
  request
} from '../../request/index.js';
var app = getApp()
var QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
// 定义全局变量
var windowHeight = 0;
var windowWidth = 0;
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mapId: "myMap",
    //中心指针，不随着地图拖动而移动
    controls: [],
    scale: 14,
    // 控制按钮是否隐藏
    hideFlag: false,
    // markers
    markers: [],
    //搜索到的中心区域地址信息
    centerAddressBean: null,
    selectAddress: '',
    //当前省份
    currentProvince: '',
    //当前城市
    currentCity: '',
    //当前区县
    currentDistrict: '',
    // 控制添加标记view的隐藏与显示
    addMarkFlag: false,
    // 用户搜索地址
    uerSelectedAddress: '',
    // 用户搜索经纬度
    userSelectedLon: '',
    userSelectedLat: '',
    // 控制详情页开关
    showModalStatus: false,
    // 详情页动画
    animationData: '',
    // 点击之后的marker的标题
    selectedMarkerTitle: '',
    // 点击之后的markerID
    selectedMarkerID: '',
    // 点击之后的marker地址
    selectedMarkerLocation: '',
    // 是否逆地址解析
    reverseFlag: false,
    // 控制按钮是否隐藏
    hideFlag: false,
    // 控制图钉隐藏
    showControl: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    console.log('进入了MapPage , onLoad')

    // 初始化SDK
    this.loadSdk()
    // 进入地图时显示自己的位置
    wx.getLocation({
      success: (res) => {
        this.setData({
          userSelectedLon: res.longitude,
          userSelectedLat: res.latitude
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.mapCtx = wx.createMapContext('myMap')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    // 拿地图数据并赋值激活地图的ID
    // let resMap = await request({
    //   url: '/map'
    // })
    // app.globalData.mapGlobal = resMap.data.data
    console.log('当前全局图层-点数据：', app.globalData.layerGlobal)
    this.setData({
      markers: this.getActiveMarkers(app.globalData.layerGlobal)
    })
    console.log('当前全局点数据：', this.data.markers)
    if (app.globalData.searchMarkerLon && app.globalData.searchMarkerLat) {
      this.setData({
        userSelectedLat: app.globalData.searchMarkerLat,
        userSelectedLon: app.globalData.searchMarkerLon,
        scale: 16
      })
    }
    console.log('MapPage Show!')
    // 获取激活的点
    let activeMarkers = [];
    if (app.globalData.layerGlobal) {
      activeMarkers = this.getActiveMarkers(app.globalData.layerGlobal)
    }
    // 赋值显示
    this.setData({
      markers: activeMarkers
    })
    // 获取markerCount
    if (app.globalData.layerGlobal) {
      app.globalData.layerGlobal.map((v, i) => {
        v.markerCount = v.markerList.length
      })
    }
    if (app.globalData.addMarkerSuccessFlag == true) {
      this.cancel_mark()
      app.globalData.addMarkerSuccessFlag = false
    }
    if (app.globalData.deleteMarkerSuccessFlag == true) {
      this.setData({
        showModalStatus: false
      })
      app.globalData.deleteMarkerSuccessFlag == false
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: async function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 从全局数据中获取激活的点
  getActiveMarkers(data) {
    let activeMarkers = [];
    if (data) {
      data.map((v, i) => {
        if (v.isVisible && v.markerList) {
          v.markerList.map(v => activeMarkers.push(v))
        }
      })
    }
    return activeMarkers;
  },
  // 初始化QQ地图SDK
  loadSdk: function () {
    qqmapsdk = new QQMapWX({
      key: 'UKWBZ-EAFWF-AJ7JX-NFAPL-TFHV7-RNB4V'
    });
  },
  // 改变地图高度
  changeMapHeight: function () {
    wx.getSystemInfo({
      success: (res) => {
        windowHeight = res.windowHeight;
        windowWidth = res.windowWidth;
        this.setMapHeight();
      },
    })
  },
  // 设置高度
  setMapHeight: function (params) {
    this.setData({
      mapHeight: (windowHeight) + 'px'
    })
  },
  // 拖动地图回调
  regionChange: function (res) {
    if (res.type == "end" && (res.causedBy == 'scale' || res.causedBy == 'drag')) {
      this.mapCtx.getCenterLocation({
        success: (res) => {
          console.log('getCenterLocation----------------------->');
          this.updateCenterLocation(res.latitude, res.longitude)
          // 调用逆地址解析
          if (this.data.reverseFlag == true) {
            this.reverse();
          }
        }
      })
    }
  },
  // 逆地址解析
  reverse: function () {
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: this.data.centerLatitude,
        longitude: this.data.centerLongitude
      },
      success: (res) => {
        console.log(res);
        this.setData({
          centerAddressBean: res.result,
          selectAddress: res.result.formatted_addresses.recommend,
          currentProvince: res.result.address_component.province,
          currentCity: res.result.address_component.city,
          currentDistrict: res.result.address_component.district,
          addMarkFlag: true,

          userSelectedLat: this.data.centerLatitude,
          userSelectedLon: this.data.centerLongitude
        })
      },
      fail: (res) => {
        console.log(res)
      }
    })
  },
  // 得到中心点坐标
  getCenterLocation: function () {
    this.mapCtx.getCenterLocation({
      success: (res) => {
        console.log('getCenterLocation----------------------->');
        this.updateCenterLocation(res.latitude, res.longitude)
      }
    })
  },
  // 更新坐标
  updateCenterLocation: function (latitude, longitude) {
    this.setData({
      centerLatitude: latitude,
      centerLongitude: longitude
    })
  },
  // 显示标记
  textShow: function () {
    // 遍历marker数据
    let totalMarkerCopy = JSON.parse(JSON.stringify(this.data.markers));
    totalMarkerCopy.map((value, index) => {
      if (value.callout) {
        if (value.callout.display == 'BYCLICK') {
          value.callout.display = 'ALWAYS'
        } else if (value.callout.display == 'ALWAYS') {
          value.callout.display = 'BYCLICK'
        }
      }
    })
    this.setData({
      markers: totalMarkerCopy
    })
  },
  // 缩放视野展示所有经纬度
  includePoints: function () {
    this.mapCtx.includePoints({
      padding: [10],
      points: [{
        latitude: 3.86,
        longitude: 73.66,
      }, {
        latitude: 53.55,
        longitude: 135.05,
      }]
    })
  },
  // 跳转到当前位置
  moveToLocation: function (e) {
    this.mapCtx.moveToLocation();
    this.setData({
      scale: 14
    })
    console.log('跳转 当前位置 被调用了')
  },
  // 地图切换
  mapTap: function () {
    wx.navigateTo({
      url: '../../pages/mapListPage/mapListPage',
    })
  },
  // 图层
  layerTap: function () {
    wx.navigateTo({
      url: '../../pages/layerListPage/layerListPage',
    })
  },
  // 点击画点调用逆地址解析
  drawMarker: function () {
    // 关闭按钮
    this.setData({
      hideFlag: true
    })
    this.mapCtx.getCenterLocation({
      success: (res) => {
        this.updateCenterLocation(res.latitude, res.longitude)
        // 开启缩放地图逆地址解析
        this.setData({
          reverseFlag: true
        })
        let controlsWidth = 40;
        let controlsHeight = 48;
        //设置中间部分指针
        this.setData({
          showControl: true
        })
        this.setData({
          controls: [{
            id: 1,
            iconPath: '../../icons/center-location.png',
            position: {
              left: (windowWidth - controlsWidth) / 2,
              top: (windowHeight) / 2 - controlsHeight * 3 / 4,
              width: controlsWidth,
              height: controlsHeight
            },
            clickable: true
          }]
        })
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: this.data.centerLatitude,
            longitude: this.data.centerLongitude
          },
          success: (res) => {
            console.log(res);
            this.setData({
              centerAddressBean: res.result,
              selectAddress: res.result.formatted_addresses.recommend,
              currentProvince: res.result.address_component.province,
              currentCity: res.result.address_component.city,
              currentDistrict: res.result.address_component.district,
              addMarkFlag: true,

              userSelectedLat: this.data.centerLatitude,
              userSelectedLon: this.data.centerLongitude
            })
          },
          fail: (res) => {
            console.log(res)
          }
        })
      }
    })
  },
  // 用户点击取消
  cancel_mark: function () {
    // 开启按钮
    this.setData({
      hideFlag: false
    })
    this.setData({
      addMarkFlag: false,
      controls: [],
      showControl: false
    })
    // 关闭逆地址解析
    this.setData({
      reverseFlag: false
    })
  },
  // 添加mark
  add_mark: function () {
    // 首先判断是否登录
    if (app.globalData.userInfo == null) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，是否跳转登录？',
        success: res => {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/myPage/myPage',
            })
          }
        }
      })
    } else {
      // 判断权限
      if (app.globalData.teamUserRight != 2) {
        wx.showModal({
          title: '提示',
          content: '您还没有编辑权限！请联系管理员'
        })
      } else {
        //跳转到添加点页面
        wx.navigateTo({
          url: '../../pages/addMarkerPage/addMarkerPage?address=' + this.data.selectAddress + '&addMarkLon=' + this.data.userSelectedLon + '&addMarkLat=' + this.data.userSelectedLat,
        })
      }
    }
  },
  // 搜索地点
  onChangeAddress() {
    wx.chooseLocation({
      success: (res) => {
        // 关闭按钮
        this.setData({
          hideFlag: true
        })
        // 开启逆地址解析
        this.setData({
          reverseFlag: true
        })
        // 取消原有control
        this.setData({
          showControl: false
        })
        this.setData({
          controls: []
        })
        this.setData({
          uerSelectedAddress: res.address,
          userSelectedLat: res.latitude,
          userSelectedLon: res.longitude,

          addMarkFlag: true,
          selectAddress: res.name
        });
        // 放置图钉
        this.setData({
          showControl: true
        })
        let controlsWidth = 40;
        let controlsHeight = 48;
        this.setData({
          controls: [{
            id: 1,
            iconPath: '../../icons/center-location.png',
            position: {
              left: (windowWidth - controlsWidth) / 2,
              top: (windowHeight) / 2 - controlsHeight * 3 / 4,
              width: controlsWidth,
              height: controlsHeight
            },
            clickable: true
          }]
        })
      },
      fail: (err) => {
        console.log(err);
      }
    });
  },
  // 点击marker出现详情页弹窗
  markertap: function (e) {
    // 根据marerId返回其经纬度信息
    let selectedMarkerId = e.detail.markerId;
    let selectedMarkerLat = '';
    let selectedMarkerLon = '';
    let selectedMarkerTitle = ''
    this.data.markers.map((value, index) => {
      if (value.id === selectedMarkerId) {
        selectedMarkerLat = value.latitude;
        selectedMarkerLon = value.longitude;
        selectedMarkerTitle = value.callout.content;
      }
    })
    // 逆地址解析
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: selectedMarkerLat,
        longitude: selectedMarkerLon
      },
      success: (res) => {
        this.setData({
          selectedMarkerLocation: res.result.address
        })
      },
      fail: (res) => {
        console.log(res)
      }
    })
    // 显示点属性-详细地址
    this.setData({
      selectedMarkerID: selectedMarkerId,
      selectedMarkerTitle: selectedMarkerTitle
    })
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  // 跳转到详情页
  handleDetailMarker: function () {
    wx.navigateTo({
      url: '../../pages/markerDetailPage/markerDetailPage?selectedMarkerID=' + this.data.selectedMarkerID + '&selectedMarkerTitle=' + this.data.selectedMarkerTitle + '&selectedMarkerLocation=' + this.data.selectedMarkerLocation
    })
  }
})